<template>
  <div class="order">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="orderFrom" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="到货日期：">
          <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChangeFn" />
        </el-form-item>
        <el-form-item label="供应商">
          <pb-select v-model="orderFrom.supplierId" placeholder="请选择供应商" keys="supplierId" label="supplierName"
            :options="PurchaseList" @change="setlierIdFn" />
        </el-form-item>
        <!-- <el-form-item label="状态：">
          <pb-select v-model="orderFrom.Status" placeholder="请选择状态" keys="val" label="name" :options="statusList"
            @change="changetenantIdFn" />
        </el-form-item> -->
        <el-form-item label="采购类型：">
          <pb-check :list="classList" @change="changeCheck($event)"></pb-check>
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <div class="content-box">
          <div class=" main-box ">
            <pb-table :column="planColumn" :tableData="orderData" :bottomElement="['pb-page']" :indexWidth="60">
              <template #operate="{ row }">
                <div class="flex">
                  <div v-hasPerm="'center:schemeorder:export'">
                    <PopconfirmButton @confirm="ExportSumFn(row)" text="导出"></PopconfirmButton>
                    <p class="divider mr-2 ml-2"></p>
                  </div>
                  <pb-button v-hasPerm="'center:schemeorder:view'" text size="small"
                    @click="onrefEditFn(row)">明细</pb-button>
                </div>
              </template>
            </pb-table>
            <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
              @onChange="onPagesChange" :total="pages.total"></pb-pagination>
          </div>
        </div>
      </pb-card>
    </div>
    <Edit ref="refEdit" />
  </div>
</template>
<script setup lang="ts">
import Edit from './edit/index.vue'
import { formattedDate } from '@/utils/moment'
import {
  GetPurchaseListApi,
  GetSummaryListApi, ExportSummaryrBlodApi
} from '@/api/Purchasing'
import { clearObjKey } from '@/utils/fliter'
const ExportSumFn = (row: any) => {
  ExportSummaryrBlodApi({
    purchaseSummaryId: row.purchaseSummaryId
  }).then((response: any) => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      // console.log("Decoded filename:", decodedFilename);
    } else {
      decodedFilename = "采购汇总" + new Date().getTime() + '.xlsx'
      // 如果没有找到包含文件名的部分，输出警告信息
      // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const setlierIdFn = (event: any) => {
  // console.log(event[0].supplierId, '221321')
  orderFrom.supplierId = event[0].supplierId
  GetOrderListFn()
}
const PurchaseList = ref([] as any)
const refEdit = ref(null as any)
const onrefEditFn = (row: any) => {
  refEdit.value.show(JSON.parse(JSON.stringify(row)))
}
const changeCheck = (eve: any) => {
  // console.log(eve, '22')
  orderFrom.purchaseType = eve.val
  GetOrderListFn()
}
const classList = ref([
  { label: '全部', val: '', checked: true },
  { label: '周采购', val: 'weekPlan', checked: false },
  { label: '月采购', val: 'monthPlan', checked: false },
])
const orderFrom = reactive({
  supplierId: '',
  deliveryStartDate: '',
  deliveryStopDate: '',
  purchaseType: ''
})
const refDetails = ref(null as any)
const searchFn = () => {
  GetOrderListFn()
}
const resetFn = () => {
  value1.value = ''
  clearObjKey(orderFrom)
  GetOrderListFn()
}
const orderData = ref([] as any)
const planColumn = [
  {
    key: "deliveryDate",
    name: "到货日期",
    align: "right",
  },
  {
    key: "supplierName",
    name: "供应商",
  },
  {
    key: "supplyTenantName",
    name: "关联食堂",
  },
  {
    key: 'purchaseTypeName',
    name: "采购类型",
  },
  {
    key: 'createTime',
    name: "创建日期",
    align: "right",
  },
  {
    width: 180,
    slot: "operate",
    name: "操作",
  },
]
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  GetOrderListFn()
}
const timeChangeFn = (time: any) => {
  orderFrom.deliveryStartDate = formattedDate(time[0], 'YYYY-MM-DD')
  orderFrom.deliveryStopDate = formattedDate(time[1], 'YYYY-MM-DD')
}
const GetOrderListFn = () => {
  GetSummaryListApi({
    "currentPage": 1,
    "pageSize": 10,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    ...orderFrom
  }).then(res => {
    orderData.value = res.data.records
    pages.value.total = res.data.total
  })
}
const value1 = ref('')
onMounted(() => {
  GetOrderListFn()
  GetPurchaseListApi({ "pageSize": -1, }).then(res => {
    let Unshiftlist = [{
      supplierName: '全部',
      supplierId: ''
    }]
    PurchaseList.value = Unshiftlist.concat(res.data.records)
  })
})
</script>
<style lang="scss" scoped>
.order {
  .content-box {
    height: 100%;
    display: flex;
    flex-direction: column;

    .main-box {
      padding: 16px;
      box-sizing: border-box;
    }
  }
}
</style>
